//
//  OASendMessageViewController.m
//  OASystem
//
//  Created by zhoupengfei on 15/3/28.
//  Copyright (c) 2015年 zpf. All rights reserved.
//
#import "yjTableViewCell.h"
#import "OASendMessageViewController.h"
#import "GDataDefines.h"
#import "UnDoneModel.h"
#import "OAUnDoneListCell.h"
#import "OASendMessageDetailController.h"
#import "OANewEmailController.h"
@interface OASendMessageViewController ()
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)int totalCounts; //总条数
@property(nonatomic,assign)int currentPage; //当前页
@property(nonatomic,strong)NSDictionary * adic;

@end

@implementation OASendMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
            self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.tableView addHeaderWithCallback:^{
        self.currentPage = 1;
        [self loadData]; //加载网络数据
    }];
    [self.tableView headerBeginRefreshing];
    
    [self.tableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
            [self loadMore];
            
        }else{
            
            [self.tableView footerEndRefreshing];
            [self.view makeToast:@"没有更多了"];
            
        }
        
    }];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"refreshData" object:nil];
}
-(void)refreshData{
    self.currentPage = 1;
    [self loadData];
}


-(NSMutableArray*)dataArray{
    if (_dataArray == nil) {
        _dataArray =   [NSMutableArray array];
    }
    return _dataArray;
}

//-(void)setupRightItem{
//
//    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewEmail)];
//
//}
//#pragma mark 添加新的邮件
//-(void)addNewEmail{
//
//    
//}

#pragma mark 加载网络数据
-(void)loadData{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:KexchmailURL arrays:array method:KOutboxMethod success:^(id JSON) {
    NSLog(@"%@",JSON);
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
      _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
        self.totalCounts =[JSON[@"number"] intValue];

   self.title = [NSString stringWithFormat:@"发件箱(%@)",JSON[@"number"] ];

         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
            [self.view makeToast:@"暂时还没数据哦"];
        }
    } failure:^(NSError *error) {
        [self.tableView headerEndRefreshing];
        
    }];
    
}

#pragma mark 加载更多
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:KexchmailURL arrays:array method:KOutboxMethod success:^(id JSON) {
    
            NSArray *array = JSON[@"data"];

 for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
//_adic= JSON[@"display"];

self.currentPage++;
        [self.tableView footerEndRefreshing];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView footerEndRefreshing];
    }];
    
}


//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            UnDoneModel * model = [[UnDoneModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"发送时间"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            GDataXMLElement * isReadElement = [[data elementsForName:@"是否已读"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.fileId = [fileIdElement stringValue];
            model.isRead = [isReadElement stringValue];
            model.iconType = @"SendBox"; //发送箱
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue] ;
        
    }
    self.title = [NSString stringWithFormat:@"发件箱(%d)",self.totalCounts];
    return array;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UnDoneModel * model = self.dataArray[indexPath.row];
//    CGFloat height = 0;
//    CGFloat  titlesize  = [OAToolBox sizebyText:model.title font:14 minsWidth:80];
//    NSString * desstring = [NSString stringWithFormat:@"%@",model.time];
//    CGFloat dessize = [OAToolBox sizebyText:desstring font:13 minsWidth:60];;
//    height = titlesize + dessize + 20;
//    return  height;
     NSDictionary *dic = self.dataArray[indexPath.row];

    CGFloat  titleFloat  = [OAToolBox sizebyText:dic[@"subject"] font:15 minsWidth:60];

    return  titleFloat  +60+10;

//return ( KScreenHeight-64)/10;
}




#pragma mark UITableView dataScource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

 static NSString *CellIdentifier = @"Cell";  

    yjTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
  if (cell==nil) {  
        cell=[[yjTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
 NSDictionary *dic = self.dataArray[indexPath.row];
    cell.dic = dic;
    cell.adic = _adic;
    cell.number = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
    return cell;




//     if (![model.isRead isEqualToString:@"1"]) {
//         
// cell.contentView.backgroundColor = [UIColor colorWithRed:231/255.0 green:231/255.0 blue:231/255.0 alpha:1];
//        }
//        else{
//      cell.contentView.backgroundColor = [UIColor whiteColor];
//        }
 }

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
            NSDictionary *dic = self.dataArray[indexPath.row];

     UnDoneModel * model = self.dataArray[indexPath.row];
    OASendMessageDetailController * detailVC = [self.storyboard instantiateViewControllerWithIdentifier:@"NewSendDetailVCID"];
    detailVC.fileId = dic[@"unid"];
                                   detailVC.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:detailVC animated:YES];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(IBAction)sendEmail:(id)sender{
    OANewEmailController * newEmailVC = (OANewEmailController*)[self.storyboard instantiateViewControllerWithIdentifier:@"NewEmailVCID"];
    newEmailVC.type = Other;
                newEmailVC.hidesBottomBarWhenPushed = YES;
                                   newEmailVC.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:newEmailVC animated:YES];
    
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
